#!/usr/bin/env bash
currentdir=$(cd $(dirname $0) && pwd)
workspace=`dirname $currentdir`

filename=`basename "$0"`
prefix="${filename%.*}"

app=$prefix
environment=production
address=0.0.0.0

bin_dir=$workspace/bin
conf_dir=$workspace/conf
log_dir=$workspace/var/log
run_dir=$workspace/var/run

spring_conf=$conf_dir/application-$environment.yml
log4j2_conf=$conf_dir/log4j2.yml

cpu_core=$([[ $(uname) = 'Darwin' ]] && sysctl -n hw.logicalcpu_max || lscpu -p | egrep -v '^#' | wc -l)

if [ $environment == "development" ] || [ $environment == "testing" ]; then
JAVA_OPTS="-DLOG_PATH=$log_dir -server"
elif [ $environment == "production" ]; then
JAVA_OPTS="-DLOG_PATH=$log_dir \
-server -Xss256k -Xms1024m -Xmx2048m -XX:MaxMetaspaceSize=256m \
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$log_dir -XX:ErrorFile=$log_dir/jvm_err.log \
-XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:ConcGCThreads=$cpu_core -XX:ParallelGCThreads=$cpu_core -XX:+ScavengeBeforeFullGC  -XX:+CMSScavengeBeforeRemark -XX:+CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=70 \
-XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:GCLogFileSize=50M -verbose:gc -XX:+PrintHeapAtGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+PrintGCApplicationStoppedTime -Xloggc:$log_dir/gc.log "
else
JAVA_OPTS="-DLOG_PATH=$log_dir -server"
fi


RUN_ARGS="--logging.config=file:$log4j2_conf         \
--server.address=$address                  \
--spring.profiles.active=$environment"

APP_NAME=$app
MODE=service
PID_FOLDER=$run_dir
LOG_FOLDER=$log_dir
LOG_FILENAME=$app.log.run